package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.project.Main3;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackageClasses = Main3.class)
@MapperScan("com.project.mapper")
@EnableTransactionManagement
public class MyBatisConfig {

    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource =new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:6789/DB?characterEncoding=utf-8&allowMultiQueries=true");
        dataSource.setUsername("root");
        dataSource.setPassword("lovo");
        dataSource.setMaxWait(1000);
        dataSource.setMinIdle(20);
        dataSource.setMaxActive(100);
        return dataSource;
    }

    @Bean("factory")
    public SqlSessionFactoryBean getFactory(){
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(this.getDataSource());
        sessionFactoryBean.setConfigLocation(
                new ClassPathResource("mybatis.cfg.xml")
        );
        return sessionFactoryBean;
    }

    @Bean
    public TransactionManager getTransaction(){
        DataSourceTransactionManager trans = new DataSourceTransactionManager();
        trans.setDataSource(this.getDataSource());
        return trans;
    }
}
